package cn.sisyphe.framework.db.routing;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by heyong on 2017/12/5 9:34
 * Description: 数据库动态路由
 *
 * @author heyong
 */
@Primary
@Component
public class DynamicRoutingDataSource extends AbstractRoutingDataSource {

    @Autowired
    private MasterDataSource masterDataSource;

    @Autowired
    private SlaveDataSource slaveDataSource;

    @Override
    protected Object determineCurrentLookupKey() {

        return DynamicDataSourceHolder.getDataSource();
    }

    /**
     * 初始化数据库配置
     */
    @PostConstruct
    public void init() {
        Map<Object, Object> targetDataSources = new HashMap<Object, Object>(2);
        targetDataSources.put(DbType.MASTER, masterDataSource.masterDataSource());
        targetDataSources.put(DbType.SLAVE, slaveDataSource.slaveDataSource());
        this.setTargetDataSources(targetDataSources);

        // 默认是主库
        this.setDefaultTargetDataSource(masterDataSource.masterDataSource());
    }
}
